package com.zhiche.wms.admin.controller.itf;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.wms.core.supports.RestfulResponse;
import com.zhiche.wms.core.supports.enums.TableStatusEnum;
import com.zhiche.wms.domain.model.base.StoreArea;
import com.zhiche.wms.domain.model.base.Storehouse;
import com.zhiche.wms.domain.model.inbound.FactoryPrepareInbound;
import com.zhiche.wms.dto.inbound.FPInboundDTO;
import com.zhiche.wms.dto.outbound.FPOutboundDTO;
import com.zhiche.wms.service.base.IStoreAreaService;
import com.zhiche.wms.service.base.IStorehouseService;
import com.zhiche.wms.service.dto.FactoryPrepareInboundVo;
import com.zhiche.wms.service.inbound.IFactoryPreInboundService;
import com.zhiche.wms.service.utils.CommonFields;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: caiHua
 * @Description: 工厂备料
 * @Date: Create in 10:03 2019/11/20
 */
@RestController
@RequestMapping(value = "/factoryStock")
public class FactoryPrepareController {

    private static final Logger LOGGER = LoggerFactory.getLogger(FactoryPrepareController.class);

    @Autowired
    private IFactoryPreInboundService iFactoryPreInboundService;
    @Autowired
    private IStorehouseService iStorehouseService;
    @Autowired
    private IStoreAreaService iStoreAreaService;

    /**
     * 工厂未备料批量入库
     */
    @RequestMapping(value = "/inboundPrepare", method = RequestMethod.POST)
    public RestfulResponse<List<String>> inboundPrepare (@RequestBody FactoryPrepareInboundVo factoryPrepareInboundVo) {
        LOGGER.info("controller:/factoryStock/inboundPrepare factoryPrepareInboundVo: {}", factoryPrepareInboundVo);
        RestfulResponse<List<String>> result = new RestfulResponse<>(0, "成功", null);
        List<String> list = iFactoryPreInboundService.prepareInbound(factoryPrepareInboundVo);
        if (CollectionUtils.isNotEmpty(list)) {
            result.setMessage("处理结果");
            result.setCode(-2);
            result.setData(list);
        }
        return result;
    }

    /**
     * 导入
     */
    @PostMapping("/importPrepareInbound")
    public RestfulResponse<Map<String, JSONArray>> importPrepareInbound (@RequestBody String data) {
        LOGGER.info("contoller:/factoryStock/importPrepareInbound data: {}", data);
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONArray arrayHeader = JSONObject.parseArray(jsonObject.getString("header"));
        if (!arrayHeader.get(arrayHeader.size() - 1).equals("备注")) {
            arrayHeader.add("导入结果");
            arrayHeader.add("备注");
        }

        JSONArray arrayRows = JSONObject.parseArray(jsonObject.getString("rows"));
        Map<String, JSONArray> map = new HashMap<>();
        for (int i = 0; i < arrayRows.size(); i++) {
            Long storeHouseId = null;
            FactoryPrepareInboundVo inboundVo = new FactoryPrepareInboundVo();
            inboundVo.setVins(StringUtils.isBlank(arrayRows.getJSONObject(i).getString("车架号")) ?
                    null : arrayRows.getJSONObject(i).getString("车架号").trim());

            if (StringUtils.isEmpty(inboundVo.getVins())) {
                arrayRows.getJSONObject(i).put("导入结果", "失败");
                arrayRows.getJSONObject(i).put("备注", "车架号为空！");
                continue;
            }
            if (StringUtils.isBlank(arrayRows.getJSONObject(i).getString("仓库"))) {
                arrayRows.getJSONObject(i).put("导入结果", "失败");
                arrayRows.getJSONObject(i).put("备注", "仓库为空！");
                continue;
            } else {
                String storeName = arrayRows.getJSONObject(i).getString("仓库").trim();
                EntityWrapper<Storehouse> wuEw = new EntityWrapper<>();
                wuEw.eq("name", storeName);
                wuEw.ne("property", TableStatusEnum.STATUS_10.getCode());
                List<Storehouse> storehouse = iStorehouseService.selectList(wuEw);
                if (CollectionUtils.isEmpty(storehouse)) {
                    arrayRows.getJSONObject(i).put("导入结果", "失败");
                    arrayRows.getJSONObject(i).put("备注", "不支持当前仓库！");
                    continue;
                } else {
                    inboundVo.setStoreHouseId(storehouse.get(0).getId());
                }
                storeHouseId = storehouse.get(0).getId();
            }
            if (StringUtils.isBlank(arrayRows.getJSONObject(i).getString("库区").trim())) {
                arrayRows.getJSONObject(i).put("导入结果", "失败");
                arrayRows.getJSONObject(i).put("备注", "库区为空！");
                continue;
            } else {
                EntityWrapper<StoreArea> areaEw = new EntityWrapper<>();
                areaEw.eq(CommonFields.STORE_HOUSE_ID.getCode(), storeHouseId);
                areaEw.eq("type",TableStatusEnum.STATUS_40.getCode());
                areaEw.eq(CommonFields.CODE.getCode(), arrayRows.getJSONObject(i).getString("库区").trim());
                StoreArea storeArea = iStoreAreaService.selectOne(areaEw);
                if (null == storeArea) {
                    arrayRows.getJSONObject(i).put("导入结果", "失败");
                    arrayRows.getJSONObject(i).put("备注", "入库库区不存在！");
                    continue;
                } else {
                    inboundVo.setAreaId(storeArea.getId());
                }
            }

            List<String> insertRes = iFactoryPreInboundService.prepareInbound(inboundVo);
            if (insertRes.size() > 0) {
                arrayRows.getJSONObject(i).put("导入结果", "失败");
                arrayRows.getJSONObject(i).put("备注", insertRes.get(0));
            } else {
                arrayRows.getJSONObject(i).put("导入结果", "成功");
                arrayRows.getJSONObject(i).put("备注", "");
            }
        }
        map.put("header", arrayHeader);
        map.put("rows", arrayRows);
        return new RestfulResponse<>(0, "导入成功", map);
    }


    /**
     * 工厂未备料出库
     */
    @RequestMapping(value = "/outboundPrepare", method = RequestMethod.POST)
    public RestfulResponse<List<String>> outboundPrepare (@RequestBody FactoryPrepareInboundVo param) {
        LOGGER.info("controller:/factoryStock/outboundPrepare param: {}", param);
        RestfulResponse<List<String>> result = new RestfulResponse<>(0, "成功", null);
        List<String> resultList = iFactoryPreInboundService.outboundPrepare(param);
        if (CollectionUtils.isNotEmpty(resultList)) {
            result.setMessage("处理结果");
            result.setCode(-2);
            result.setData(resultList);
        }
        return result;
    }

    /**
     * 工厂未备料出库列表查询
     */
    @RequestMapping(value = "/queryFactoryOutbound", method = RequestMethod.POST)
    public RestfulResponse<Page<FPOutboundDTO>> queryFactoryOutbound (@RequestBody Page<FPOutboundDTO> page) {
        LOGGER.info("controller:/factoryStock/queryFactoryOutbound param: {}", page);
        RestfulResponse<Page<FPOutboundDTO>> result = new RestfulResponse<>(0, "成功", null);
        Page<FPOutboundDTO> factoryPrepareInboundPage = iFactoryPreInboundService.queryFactoryOutbound(page);
        result.setData(factoryPrepareInboundPage);
        return result;
    }

    /**
     * 工厂未备料入库列表查询
     */
    @RequestMapping(value = "/queryFactoryInbound", method = RequestMethod.POST)
    public RestfulResponse<Page<FPInboundDTO>> queryFactoryInbound (@RequestBody Page<FPInboundDTO> page) {
        LOGGER.info("controller:/factoryStock/queryFactoryInbound param: {}", page);
        RestfulResponse<Page<FPInboundDTO>> result = new RestfulResponse<>(0, "成功", null);
        Page<FPInboundDTO> factoryPrepareInboundPage = iFactoryPreInboundService.queryFactoryInbound(page);
        result.setData(factoryPrepareInboundPage);
        return result;
    }

    /**
     * 已经有提车指令，但是有未出库车辆提示必办
     */
    @RequestMapping(value = "/queryMustMatter", method = RequestMethod.POST)
    public RestfulResponse<List<Map<String, Object>>> queryMustMatter (@RequestBody Map<String, String> param) {
        LOGGER.info("controller:/factoryStock/queryMustMatter param: {}", param);
        List<Map<String, Object>> resultList = new ArrayList<>();
        RestfulResponse<List<Map<String, Object>>> result = new RestfulResponse<>(0, "成功", null);
        Map<String, Object> factoryCount = iFactoryPreInboundService.queryMustMatter(param);
        if(null != factoryCount && !factoryCount.isEmpty()){
            resultList.add(factoryCount);
        }
        result.setData(resultList);
        return result;
    }


}
